package phoenics.upservice.restcontroller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import phoenics.alipay.AlipayConfig;
import phoenics.upservice.entity.Project;
import phoenics.upservice.entity.User;
import phoenics.upservice.entity.UserProject;
import phoenics.upservice.repository.ProjectRepo;
import phoenics.upservice.repository.UserProjectRepository;
import phoenics.upservice.repository.UserRepo;
import phoenics.upservice.service.UserService;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@RestController
@RequestMapping("/payback")
public class PayBack {
    private static org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(PayBack.class);
    @Autowired
    UserService userService;
    @Autowired
    UserProjectRepository userProjectRepository;
    @Autowired
    UserRepo userRepo;
    @Autowired
    ProjectRepo projectRepo;

    @PostMapping(value = "/alipayNotify")
    public String alipayCallback(HttpServletRequest request){
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //logger.info("name======{}, valueStr========={}",name, valueStr);
            params.put(name, valueStr);
        }
        boolean signVerified =false;
        try {
            signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.ali_public_key, AlipayConfig.input_charset, AlipayConfig.sign_type); //调用SDK验证签名
            if(signVerified){
                String outTradeNo = request.getParameter("out_trade_no").toString();
                String tradeStatus = request.getParameter("trade_status").toString();
                String total_amount = request.getParameter("total_amount").toString();
               // logger.info("out_trade_no===={}",outTradeNo);
              //  logger.info("trade_status===={}",tradeStatus);
               // logger.info("total_amount===={}",total_amount);
                //setTotalAmount
                if(tradeStatus.equals("TRADE_FINISHED")||tradeStatus.equals("TRADE_SUCCESS")){
                   // logger.info("trade id= {}",outTradeNo);
                    //String orderId=u.getId()+"_"+pid;
                    List<Long> ids=Stream.of(StringUtils.split(outTradeNo,"_")).map(id->Long.valueOf(id)).collect(Collectors.toList());
                    return createOrder(ids.get(0),ids.get(1),outTradeNo,new BigDecimal (total_amount));
                }else{
                    logger.info("tradeStatus is {}",tradeStatus);
                }
            }else{
                logger.info("signVerified= false");
            }
        } catch (AlipayApiException e) {
            logger.error("ali verifield error");
        }
        return null;
    }

    /**
     * 建立订单
     * @return
     */

    private String createOrder(Long uid, Long pid, String tradeNo, BigDecimal total_amount){
        //User userE=userService.takePrincipal();
        final String num=tradeNo;
        Optional< UserProject> up=userProjectRepository.findOneOrder(uid,pid);
        if(up.isPresent()){
        }else{
            UserProject  userProject=new UserProject();
            Optional< User> user=userRepo.findById(uid);
            Optional<Project> pr=projectRepo.findById(pid);
            boolean br=user.isPresent() && pr.isPresent();
            if(br){
                userProject.setUser(user.get());
                userProject.setProject(pr.get());
                userProject.setOrdernumber(tradeNo);
                userProject.setPrice(total_amount.floatValue());
                userProjectRepository.save(userProject);
                logger.info("order {}  success write date to database",tradeNo);
            }
            return "success";
        }
        return "";

    }
}
